<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 商品库存列表
 * @package app\cms\admin
 */
class StockNum extends Admin
{
    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		// 获取筛选
        $map = $this->getMap();
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		
		$warehouse_info = model('ErpWarehouse', 'model') -> where('type', 2) -> find();
		$warehouse_id = $warehouse_info['id'];
		$warehouse_title = $warehouse_info['title'];
		
		$map_ware = [];
		$store_warehouse_id= '';
		if($sotre_user['store_uid'] > 0){
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id = $store_warehouse_list[0];
			$map_ware[] = ['id', 'in',$store_warehouse_list];
		}
		
		foreach($map as $key => $value){
			if($value[0] == 'warehouse_id'){
				$warehouse_id = $value[2]; // 门店id
				unset($map[$key]);
			}
		}
		//数据获取
        $data = input();
		// 数据列表
		if($warehouse_id > 0){
			$warehouse_list = model('ErpGoodsWarehouseStockNum', 'model') -> where('warehouse_id', $warehouse_id) -> column('goods_id');
			$map[] = ['id', 'in', $warehouse_list];
		}
		$map = array_merge($map);
		$data_list = model('ErpGoods', 'model') -> where($map) -> order('create_time desc') -> paginate();
		
		foreach($data_list as $key => $value){
			$goods_id = $value['id'];
			$map = [];
			$map['goods_id'] = $goods_id;
			if($warehouse_id > 0)$map['warehouse_id'] = $warehouse_id;
			$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(stock_num) as stock_num,sum(frozen_num) as frozen_num,sum(available_num) as available_num,min(price) as price')->where($map)->find();//库存
			
			$data_list[$key]['stock_num']  		= isset($goods_stock['stock_num']) ? $goods_stock['stock_num'] : 0 ;
			$data_list[$key]['frozen_num'] 		= isset($goods_stock['frozen_num']) ? $goods_stock['frozen_num'] : 0 ;
			$data_list[$key]['available_num'] 	= isset($goods_stock['available_num']) ? $goods_stock['available_num'] : 0 ;
			$data_list[$key]['price'] 			= isset($goods_stock['price']) ? $goods_stock['price'] : 0 ;
			
			
			//采购单
			$map = [];
			$map[] = ['purchase_status', '=', 2];
			$purchase_id = model('ErpGoodsPurchaseOrder') -> where($map) -> column('id');//库存
			
			$map = [];
			$map[] = ['goods_id', '=', $goods_id];
			$sku_id = model('ErpGoodsSku') -> where($map) -> column('id');//sku
			
			$map = [];
			$map[] = ['sku_id', 'in', $sku_id];
			$map[] = ['purchase_id', 'in', $purchase_id];
			$purchase_info = model('ErpGoodsPurchaseOrderSku') -> field('avg(price) as avg_price') -> where($map) -> find(); //单价
			
			//单价 = 采购单该商品价格 / 商品数量
			//总价 = 采购单 单价 * 商品库存数量
			$stock_price	 = sprintf("%01.2f", $purchase_info['avg_price']);
			$stock_all_price = $stock_price * $goods_stock['stock_num'];

			$data_list[$key]['stock_price'] 		= $stock_price;
			$data_list[$key]['stock_all_price'] 	= sprintf("%01.2f", $stock_all_price);
		}
		$btn_details = [
			'title' => '库存详情',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('details', ['goods_id' => '__id__', 'warehouse_id' => $warehouse_id]),
		];
		
		$warehouse_list = model('ErpWarehouse') -> where($map_ware) -> order('sort asc, type desc, create_time desc') -> column('id, title');
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('库存列表') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('erp_goods') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['id', '商品id'],
                ['goods_name', '商品名称'],
				['stock_price', '采购均价'],
                ['stock_all_price', '库存总价'],
                ['stock_num', '总库存'],
                ['frozen_num', '冻结库存'],
                ['available_num', '可用库存'],
                ['price', '商品价格'],
                ['right_button', '操作', 'btn'],
            ])
			->setSearchArea([
                ['select', 'warehouse_id', '选择仓库', '', $warehouse_id,  $warehouse_list],
                ['text', 'goods_name', '商品名称', 'like'],
				['daterange', 'create_time', '创建时间'],
            ])
			// ->addTopSelect('warehouse_id', '选择仓库', $warehouse_list, $warehouse_id) // 添加筛选
			// ->setSearch(['goods_name' => '商品名称']) // 设置搜索参数
			->addRightButton('custom', $btn_details, true) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 商品sku产品
     * @author shiqiang
     * @return mixed
     */
	public function details($goods_id = '', $warehouse_id = 0){
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		$map = [];
		
		$url = '';
		if($goods_id > 0){
			$url = 'details/_pop/1.html';
		}
		
		if($sotre_user['store_uid'] > 0){
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$map[] = ['id', 'in',$store_warehouse_list];
			$warehouse_id = $store_warehouse_list[0];
		}
		$warehouse_list = model('ErpWarehouse') -> where($map) -> order('sort asc, type desc, create_time desc') -> column('id, title');
		
		$map = $this->getMap();
		$map1 = [];
		if($goods_id > 0) $map1[] = ['goods_id', '=', $goods_id];
		foreach($map as $key => $value){
			if($value[0] == 'warehouse_id'){
				$warehouse_id = $value[2]; // 门店id
				unset($map[$key]);
			}
		}
		$warehouse_arr = [];
		if($warehouse_id > 0){
			$where[] = ['warehouse_id', '=', $warehouse_id];
			if($goods_id > 0) $where[] = ['goods_id', '=', $goods_id];
			
			$warehouse_arr = model('ErpGoodsWarehouseStockNum', 'model') -> where($where) -> column('sku_id');
			if(!empty($warehouse_arr)) $map[] = ['id', 'in', $warehouse_arr];
		}
		$map = array_merge($map);
		$map[] = ['sku_status', '=', 1];
		$data_list = model('ErpGoodsSku', 'model') -> where($map) -> where($map1) -> order('create_time desc') -> paginate();
		if(empty($warehouse_arr) && $warehouse_id > 0) $data_list = [];
		foreach($data_list as $key => $value){
			$sku_id = $value['id'];
			// $data_list[$key]['goods_name'] = $value['goods_specifications'] != '' ? $value['goods_name'] . ' - ' . $value['goods_specifications'] : $value['goods_name'];
			
			$map = [];
			$map['sku_id'] = $sku_id;
			if($warehouse_id > 0)$map['warehouse_id'] = $warehouse_id;
			$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(stock_num) as stock_num,sum(frozen_num) as frozen_num,sum(available_num) as available_num,min(price) as price')->where($map)->find();//库存
			
			$data_list[$key]['stock_num']  		= isset($goods_stock['stock_num']) ? $goods_stock['stock_num'] : 0;
			$data_list[$key]['frozen_num'] 		= isset($goods_stock['frozen_num']) ? $goods_stock['frozen_num'] : 0;
			$data_list[$key]['available_num'] 	= isset($goods_stock['available_num']) ? $goods_stock['available_num'] : 0;
			$data_list[$key]['price'] 			= isset($goods_stock['price']) ? $goods_stock['price'] : 0 ;
			$data_list[$key]['goods_code'] 	    = $value['article_no'];
			//采购单价格
			$map = [];
			$map[] = ['purchase_status', '=', 2];
			$purchase_id = model('ErpGoodsPurchaseOrder') -> where($map) -> column('id');//库存
			
			$map = [];
			$map[] = ['purchase_id', 'in', $purchase_id];
			$map[] = ['sku_id', '=', $sku_id];
			$purchase_info = model('ErpGoodsPurchaseOrderSku') -> field('avg(price) as avg_price') -> where($map) -> find(); //单价
			
			//单价 = 采购单该商品价格 / 商品数量
			//总价 = 采购单 单价 * 商品库存数量
			$stock_price	 = sprintf("%01.2f", $purchase_info['avg_price']);
			$stock_all_price = $stock_price * $goods_stock['stock_num'];

			$data_list[$key]['stock_price'] 		= $stock_price;
			$data_list[$key]['stock_all_price'] 	= sprintf("%01.2f", $stock_all_price);
		}
		
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('库存列表') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('erp_goods') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['id', '商品id'],
				['goods_name', '商品名称'],
				['goods_code', '国际条形码'],
                ['goods_specifications', '规格名称'],
                ['stock_price', '采购均价'],
                ['stock_all_price', '成本总价'],
                ['stock_num', '总库存'],
                ['frozen_num', '冻结库存'],
                ['available_num', '可用库存'],
                ['price', '商品价格'],
            ])
			->setSearchArea([
                ['select', 'warehouse_id', '选择仓库', '', $warehouse_id,  $warehouse_list],
                ['text', 'goods_name', '商品名称', 'like'],
                ['text', 'article_no', '条形码', 'like'],
                ['text', 'goods_specifications', '规格名称', 'like'],
				['daterange', 'create_time', '创建时间'],
            ], $url)
			// ->addTopSelect('warehouse_id', '选择仓库', $warehouse_list, $warehouse_id) // 添加筛选
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
	}


	//根据条码 导入库存
	public function ceshistorenum(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $map = [];
        $map['sku_status'] = 0; //未添加的库存
        $data_list = model('ErpBarcodeStockNum') -> where($map) -> order('id desc') -> paginate();

        $btn_excel = [
            'title' => '导入库存',
            'icon'  => 'fa fa-plus-circle',
            'class' => 'btn btn-primary',
            'href'  => url('upload_excel'),
        ];
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('库存列表') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('erp_goods') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['id', 'ID'],
                ['article_no', '条形码'],
                ['stock_num', '库存数量'],
            ])
            ->addTopButton('btn_excel', $btn_excel) // 批量添加顶部按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    public function upload_excel(){
        // 保存数据
		$this -> excel_stock_num();
        /* if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');

            // 接收附件 ID
            $excel_file = $this->request->post('excel');
            // 获取附件 ID 完整路径
            $full_path = getcwd() . get_file_path($excel_file);
            // 只导入的字段列表
            $fields = [
				'stock_num'  	=> '库存数量',
                'article_no'  	=> '货号',
            ];
            // 调用插件('插件',[路径,导入表名,字段限制,类型,条件,重复数据检测字段])
            $import = plugin_action('Excel/Excel/import', [$full_path, 'erp_barcode_stock_num', $fields, $type = 0, $where = null, $main_field = 'article_no']);
            // 失败或无数据导入
            if ($import['error']){
                $this->error($import['message']);
            }
            $this -> excel_stock_num();
            // 导入成功
            $this->success($import['message'], '', '_parent_reload');
        }
        return ZBuilder::make('form')
            ->setPageTitle('导入Excel')
            ->addFormItems([ // 添加上传 Excel
                ['file', 'excel', '上传文件'],
            ])
            ->fetch(); */
    }
    public function excel_stock_num(){
	    $warehouse_id = 17; //仓库id
        //xm_erp_barcode_stock_num
        $map = [];
        $map[] = ['sku_status', '=', 0];
        $map[] = ['article_no', 'neq', ''];
        $barcodeStockNum = model('ErpBarcodeStockNum') -> where($map) -> column('id,article_no,stock_num');
        foreach($barcodeStockNum as $key => $value){
            //查 goods_id
            $map = [];
            $map['article_no'] = $value['article_no'];
            $sku_info = model('ErpGoodsSku') -> where($map) -> find();
            if(!empty($sku_info) && ($value['stock_num'] > 0 && is_numeric($value['stock_num']))){
                //更新库存
                $goods_id   = $sku_info['goods_id'];
                $sku_id     = $sku_info['id'];

                $map = [];
                $map['warehouse_id'] = $warehouse_id;
                $map['goods_id']    = $goods_id;
                $map['sku_id']      = $sku_id;
                $stock_info = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();

                if(!empty($stock_info)){
                    $map = [];
                    $map['warehouse_id'] = $warehouse_id;
                    $map['goods_id']    = $goods_id;
                    $map['sku_id']      = $sku_id;
                    //增加
                    $stock_num      = $stock_info['stock_num'] + $value['stock_num'];
                    $available_num  = $stock_info['available_num'] + $value['stock_num'];

                    $data = [];
                    $data['stock_num']      = $stock_num;
                    $data['available_num']  = $available_num;
                    $res = model('ErpGoodsWarehouseStockNum') ->update($data, $map);
                }else{
                    //新建
                    $data = [];
                    $data['warehouse_id']   = $warehouse_id;
                    $data['goods_id']       = $goods_id;
                    $data['sku_id']         = $sku_id;
                    $data['stock_num']      = $value['stock_num'];
                    $data['frozen_num']     = 0;
                    $data['available_num']  = $value['stock_num'];
                    $data['price']          = $sku_info['price'];
                    $res = model('ErpGoodsWarehouseStockNum') -> isUpdate(false) ->data($data, true) -> save();
                }
                //标记成功
                if($res){
                    $map = [];
                    $map['id'] = $key;
                    $data = [];
                    $data['sku_status'] = 1;
                    model('ErpBarcodeStockNum') ->update($data, $map);
                }
            }
        }
		
		$this->success('导入成功', cookie('__forward__'));
    }
}

